package com.sxr.servlet.impl;

import com.sxr.file.FileResponse;
import com.sxr.integration.SecureFileRequest;
import com.sxr.integration.SecureFileService;
import com.sxr.integration.util.JsonUtils;
import com.sxr.servlet.ServletFileService;
import com.sxr.servlet.util.ServletRequestParser;
import com.sxr.servlet.util.ServletResponseWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 默认Servlet文件服务实现
 * 将Servlet API适配到核心业务逻辑
 *
 * @author SXR
 * @since 1.0.0
 */
public class DefaultServletFileService implements ServletFileService {

    private final SecureFileService secureFileService;
    private final ServletRequestParser requestParser;
    private final ServletResponseWriter responseWriter;

    public DefaultServletFileService(SecureFileService secureFileService,ServletRequestParser requestParser) {
        this.secureFileService = secureFileService;
        this.requestParser = requestParser;
        this.responseWriter = new ServletResponseWriter();
    }

    @Override
    public void handleSecureDownload(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            // 解析Servlet请求为业务请求
            SecureFileRequest fileRequest = requestParser.parseSecureFileRequest(request, false);

            // 调用核心业务逻辑
            FileResponse fileResponse = secureFileService.handleSecureDownload(fileRequest);

            // 将业务响应写入Servlet响应
            responseWriter.writeFileResponse(fileResponse, response);

        } catch (Exception e) {
            handleError(response, 500, "Internal server error: " + e.getMessage());
        }
    }

    @Override
    public void handleSecurePreview(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            // 解析Servlet请求为业务请求
            SecureFileRequest fileRequest = requestParser.parseSecureFileRequest(request, true);

            // 调用核心业务逻辑
            FileResponse fileResponse = secureFileService.handleSecurePreview(fileRequest);

            // 将业务响应写入Servlet响应
            responseWriter.writeFileResponse(fileResponse, response);

        } catch (Exception e) {
            handleError(response, 500, "Internal server error: " + e.getMessage());
        }
    }




    /**
     * 处理错误响应
     */
    private void handleError(HttpServletResponse response, int statusCode, String message) throws IOException {
        response.setStatus(statusCode);
        response.setContentType("application/json;charset=UTF-8");

        String errorJson = JsonUtils.buildErrorResponse(message);
        response.getWriter().write(errorJson);
    }


}
